<template>
  <div class="document-template">
    <div class="header-actions">
      <h1>文档模板管理</h1>
      <el-button type="primary" @click="openDialog('add')">添加模板</el-button>
    </div>

    <el-table v-loading="loading" :data="templateList" border style="width: 100%">
      <el-table-column prop="name" label="模板名称" min-width="150" />
      <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
      <el-table-column label="创建时间" min-width="170">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" min-width="170">
        <template #default="{ row }">
          {{ formatDate(row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handlePreview(row)">预览</el-button>
          <el-button type="warning" size="small" @click="openDialog('edit', row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑模板对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加模板' : '编辑模板'"
      width="60%"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        label-width="100px"
        class="template-form"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>

        <el-form-item label="模板内容" prop="content">
          <el-tabs v-model="editorTab">
            <el-tab-pane label="编辑" name="edit">
              <div class="editor-container">
                <el-input
                  v-model="templateForm.content"
                  type="textarea"
                  :rows="15"
                  placeholder="请输入模板内容 (支持 Markdown 格式)"
                />
              </div>
            </el-tab-pane>
            <el-tab-pane label="预览" name="preview">
              <div class="preview-container">
                <div v-html="renderedContent" class="markdown-body"></div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>

        <el-form-item label="变量说明">
          <div class="variables-info">
            <p>在模板中可以使用以下变量格式：</p>
            <ul class="variables-list">
              <li><code>{{vuln.id}}</code> - 漏洞ID</li>
              <li><code>{{vuln.name}}</code> - 漏洞名称</li>
              <li><code>{{vuln.cve}}</code> - CVE编号</li>
              <li><code>{{verification.time}}</code> - 验证时间</li>
              <li><code>{{verification.status}}</code> - 验证状态</li>
              <li><code>{{verification.result}}</code> - 验证结果</li>
              <li><code>{{verification.logs}}</code> - 验证日志</li>
            </ul>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="submitTemplateForm" :loading="submitting">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="模板预览" width="70%">
      <div class="template-preview">
        <div v-html="previewContent" class="markdown-body"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { marked } from 'marked'
import { 
  getDocumentTemplates, 
  getDocumentTemplateDetail, 
  createDocumentTemplate, 
  updateDocumentTemplate, 
  deleteDocumentTemplate 
} from '@/api/vulnVerification'

// 表格数据
const loading = ref(false)
const templateList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const submitting = ref(false)

// 预览对话框
const previewDialogVisible = ref(false)
const previewContent = ref('')

// 编辑器标签页
const editorTab = ref('edit')

// 表单引用
const templateFormRef = ref(null)

// 表单数据
const templateForm = reactive({
  id: '',
  name: '',
  description: '',
  content: ''
})

// 表单验证规则
const templateRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '不超过 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' }
  ]
}

// 渲染后的内容
const renderedContent = computed(() => {
  try {
    return marked(templateForm.content || '')
  } catch (error) {
    console.error('Markdown 渲染错误', error)
    return '<p>预览渲染错误</p>'
  }
})

// 获取模板列表
const fetchTemplateList = async () => {
  loading.value = true
  try {
    const { data } = await getDocumentTemplates()
    templateList.value = data.items
    total.value = data.total
  } catch (error) {
    console.error('获取文档模板列表失败', error)
    ElMessage.error('获取文档模板列表失败')
  } finally {
    loading.value = false
  }
}

// 获取模板详情
const fetchTemplateDetail = async (id) => {
  try {
    const { data } = await getDocumentTemplateDetail(id)
    return data
  } catch (error) {
    console.error('获取模板详情失败', error)
    ElMessage.error('获取模板详情失败')
    return null
  }
}

// 打开对话框
const openDialog = async (type, row) => {
  dialogType.value = type
  resetForm()
  
  if (type === 'edit' && row) {
    // 编辑时，先获取详情
    const detail = await fetchTemplateDetail(row.id)
    if (detail) {
      templateForm.id = detail.id
      templateForm.name = detail.name
      templateForm.description = detail.description
      templateForm.content = detail.content
    }
  }
  
  dialogVisible.value = true
}

// 关闭对话框
const handleCloseDialog = () => {
  if (submitting.value) return
  
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  if (templateFormRef.value) {
    templateFormRef.value.resetFields()
  }
  
  templateForm.id = ''
  templateForm.name = ''
  templateForm.description = ''
  templateForm.content = ''
  editorTab.value = 'edit'
}

// 提交表单
const submitTemplateForm = () => {
  if (templateFormRef.value) {
    templateFormRef.value.validate(async (valid) => {
      if (valid) {
        submitting.value = true
        try {
          if (dialogType.value === 'add') {
            // 创建模板
            await createDocumentTemplate({
              name: templateForm.name,
              description: templateForm.description,
              content: templateForm.content
            })
            ElMessage.success('模板创建成功')
          } else {
            // 更新模板
            await updateDocumentTemplate({
              id: templateForm.id,
              name: templateForm.name,
              description: templateForm.description,
              content: templateForm.content
            })
            ElMessage.success('模板更新成功')
          }
          
          dialogVisible.value = false
          fetchTemplateList()
        } catch (error) {
          console.error('保存模板失败', error)
          ElMessage.error('保存模板失败')
        } finally {
          submitting.value = false
        }
      }
    })
  }
}

// 预览模板
const handlePreview = async (row) => {
  try {
    // 获取详细内容
    const detail = await fetchTemplateDetail(row.id)
    if (detail) {
      // 替换变量为示例值
      let content = detail.content
        .replace(/{{vuln\.id}}/g, 'CVE-2021-44228')
        .replace(/{{vuln\.name}}/g, 'Log4j 远程代码执行漏洞')
        .replace(/{{vuln\.cve}}/g, 'CVE-2021-44228')
        .replace(/{{verification\.time}}/g, '2023-06-15 14:30:00')
        .replace(/{{verification\.status}}/g, '验证成功')
        .replace(/{{verification\.result}}/g, '目标系统成功触发了漏洞')
        .replace(/{{verification\.logs}}/g, '14:30:00 开始验证\n14:30:05 发送测试请求\n14:30:10 成功检测到漏洞响应\n14:30:15 完成验证')
      
      // 渲染 Markdown
      // previewContent.value = marked(content)
      // previewDialogVisible.value = true
    }
  } catch (error) {
    console.error('预览模板失败', error)
    ElMessage.error('预览模板失败')
  }
}

// 删除模板
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该模板吗？此操作不可逆', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDocumentTemplate(row.id)
      ElMessage.success('删除成功')
      fetchTemplateList()
    } catch (error) {
      console.error('删除模板失败', error)
      ElMessage.error('删除模板失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '--'
  return dateStr
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTemplateList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTemplateList()
}

// 组件挂载时加载数据
onMounted(() => {
  // fetchTemplateList()
})
</script>

<style lang="scss" scoped>
.document-template {
  padding: 20px;
  
  .editor-container, .preview-container {
    min-height: 300px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
  }
  
  .preview-container {
    max-height: 500px;
    overflow-y: auto;
  }
  
  .markdown-body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
    padding: 16px;
    line-height: 1.5;
    word-wrap: break-word;
    
    h1, h2, h3, h4, h5, h6 {
      margin-top: 24px;
      margin-bottom: 16px;
      font-weight: 600;
      line-height: 1.25;
    }
    
    h1 {
      font-size: 2em;
    }
    
    h2 {
      font-size: 1.5em;
    }
    
    p {
      margin-top: 0;
      margin-bottom: 16px;
    }
    
    pre {
      padding: 16px;
      overflow: auto;
      background-color: #f6f8fa;
      border-radius: 3px;
    }
    
    code {
      padding: 0.2em 0.4em;
      margin: 0;
      font-size: 85%;
      background-color: rgba(27, 31, 35, 0.05);
      border-radius: 3px;
    }
  }
  
  .variables-info {
    code {
      padding: 2px 5px;
      background-color: #f6f8fa;
      border-radius: 3px;
      font-family: monospace;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
  }
}
</style> 